package com.liam.rabbitmqdemo.rabbitmq.topic;

import com.liam.rabbitmqdemo.rabbitmq.constant.Constants;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: LiamLMK
 * @CreateTime: 2025-03-03
 * @Description:
 * @Version: 1.0
 */

public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1. 创建连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT); // 需要提前开放端口号
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST); // 虚拟主机
        Connection connection = connectionFactory.newConnection();
        // 2. 创建channel
        Channel channel = connection.createChannel();
        // 3. 声明队列（如有队列 可省略，如不存在 则创建）
        channel.queueDeclare(Constants.TOPIC_QUEUE1, true, false, false, null);
//        channel.queueDeclare(Constants.FANOUT_QUEUE2, true, false, false, null);
        // 4. 消费消息

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            // 从队列中收到消息，就会执行的方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息：" + new String(body));
            }
        };
        channel.basicConsume(Constants.TOPIC_QUEUE1, true, consumer);

        // 5. 释放资源
//        Thread.sleep(2000);
//        channel.close();
//        connection.close();
    }
}
